// 个人财务管理系统 - JavaScript功能

// 等待DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 消息提示自动消失
    setupAutoDismissAlerts();
    
    // 表单验证
    setupFormValidation();
    
    // 分类切换逻辑
    setupCategoryToggle();
    
    // 数字输入格式化
    setupNumberFormatting();
    
    // 平滑滚动
    setupSmoothScroll();
    
    // 日期选择器默认值
    setupDatePickers();
    
    // 表格排序功能
    setupTableSorting();
});

// 设置消息提示自动消失
function setupAutoDismissAlerts() {
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(alert => {
        setTimeout(() => {
            alert.classList.add('fade');
            alert.classList.remove('show');
            setTimeout(() => {
                alert.remove();
            }, 500);
        }, 5000); // 5秒后自动消失
    });
}

// 设置表单验证
function setupFormValidation() {
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(event) {
            let isValid = true;
            
            // 验证必填字段
            const requiredFields = form.querySelectorAll('[required]');
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    isValid = false;
                    field.classList.add('border-danger');
                    // 添加错误提示
                    let errorElement = field.nextElementSibling;
                    if (!errorElement || !errorElement.classList.contains('text-danger')) {
                        errorElement = document.createElement('div');
                        errorElement.className = 'text-danger text-sm mt-1';
                        errorElement.textContent = '此字段为必填项';
                        field.parentNode.insertBefore(errorElement, field.nextSibling);
                    }
                } else {
                    field.classList.remove('border-danger');
                    // 移除错误提示
                    let errorElement = field.nextElementSibling;
                    if (errorElement && errorElement.classList.contains('text-danger')) {
                        errorElement.remove();
                    }
                }
            });
            
            // 验证金额字段
            const amountFields = form.querySelectorAll('input[name="amount"]');
            amountFields.forEach(field => {
                if (field.value && (isNaN(field.value) || parseFloat(field.value) <= 0)) {
                    isValid = false;
                    field.classList.add('border-danger');
                    // 添加错误提示
                    let errorElement = field.nextElementSibling;
                    if (!errorElement || !errorElement.classList.contains('text-danger')) {
                        errorElement = document.createElement('div');
                        errorElement.className = 'text-danger text-sm mt-1';
                        errorElement.textContent = '请输入有效的金额';
                        field.parentNode.insertBefore(errorElement, field.nextSibling);
                    }
                }
            });
            
            if (!isValid) {
                event.preventDefault();
                // 滚动到第一个错误字段
                const firstError = form.querySelector('.border-danger');
                if (firstError) {
                    firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    firstError.focus();
                }
            }
        });
        
        // 输入时移除错误状态
        const inputFields = form.querySelectorAll('input, select, textarea');
        inputFields.forEach(field => {
            field.addEventListener('input', function() {
                this.classList.remove('border-danger');
                let errorElement = this.nextElementSibling;
                if (errorElement && errorElement.classList.contains('text-danger')) {
                    errorElement.remove();
                }
            });
        });
    });
}

// 设置分类切换逻辑
function setupCategoryToggle() {
    const transactionTypeSelects = document.querySelectorAll('select[name="type"]');
    transactionTypeSelects.forEach(select => {
        select.addEventListener('change', function() {
            const type = this.value;
            const categorySelect = document.querySelector('select[name="category"]');
            
            if (categorySelect && window.categoryOptions) {
                // 清空现有选项
                categorySelect.innerHTML = '<option value="" disabled selected>请选择类别</option>';
                
                // 添加对应类型的选项
                const options = window.categoryOptions[type];
                if (options) {
                    options.forEach(option => {
                        const optionElement = document.createElement('option');
                        optionElement.value = option.id;
                        optionElement.textContent = option.name;
                        categorySelect.appendChild(optionElement);
                    });
                }
            }
        });
        
        // 触发初始变化
        select.dispatchEvent(new Event('change'));
    });
}

// 设置数字输入格式化
function setupNumberFormatting() {
    const numberInputs = document.querySelectorAll('input[type="number"], input[name="amount"]');
    numberInputs.forEach(input => {
        input.addEventListener('blur', function() {
            if (this.value) {
                const value = parseFloat(this.value);
                if (!isNaN(value)) {
                    // 保留2位小数
                    this.value = value.toFixed(2);
                }
            }
        });
    });
}

// 设置平滑滚动
function setupSmoothScroll() {
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                targetElement.scrollIntoView({ behavior: 'smooth' });
            }
        });
    });
}

// 设置日期选择器默认值
function setupDatePickers() {
    const dateInputs = document.querySelectorAll('input[type="date"]');
    const today = new Date().toISOString().split('T')[0];
    
    dateInputs.forEach(input => {
        // 如果没有设置值，使用今天的日期
        if (!input.value) {
            input.value = today;
        }
        
        // 设置最大日期为今天
        if (!input.max) {
            input.max = today;
        }
    });
}

// 设置表格排序功能
function setupTableSorting() {
    const tables = document.querySelectorAll('table');
    tables.forEach(table => {
        const headers = table.querySelectorAll('th');
        headers.forEach((header, index) => {
            // 只有包含数据的列才添加排序功能
            const dataType = getColumnDataType(table, index);
            if (dataType) {
                header.classList.add('sortable');
                header.style.cursor = 'pointer';
                header.setAttribute('data-sort-index', index);
                header.setAttribute('data-sort-direction', 'asc');
                
                // 添加排序图标
                const sortIcon = document.createElement('span');
                sortIcon.className = 'ml-2';
                sortIcon.innerHTML = ' <i class="fa fa-sort"></i>';
                header.appendChild(sortIcon);
                
                // 添加点击事件
                header.addEventListener('click', function() {
                    sortTable(table, index, dataType);
                });
            }
        });
    });
}

// 获取列的数据类型
function getColumnDataType(table, columnIndex) {
    const rows = table.querySelectorAll('tbody tr');
    if (rows.length === 0) return null;
    
    // 检查前几个单元格来确定数据类型
    let isNumber = true;
    let isDate = true;
    
    for (let i = 0; i < Math.min(rows.length, 10); i++) {
        const cell = rows[i].querySelectorAll('td')[columnIndex];
        if (cell) {
            const text = cell.textContent.trim();
            
            // 检查是否为数字（包括货币格式）
            const numValue = parseFloat(text.replace(/[^0-9.-]/g, ''));
            if (isNaN(numValue)) {
                isNumber = false;
            }
            
            // 检查是否为日期
            if (isValidDate(text)) {
                isDate = isDate && true;
            } else {
                isDate = false;
            }
        }
    }
    
    if (isNumber) return 'number';
    if (isDate) return 'date';
    return 'text';
}

// 检查是否为有效日期
function isValidDate(dateString) {
    const regex = /^\d{4}-\d{2}-\d{2}$/;
    if (!regex.test(dateString)) return false;
    
    const date = new Date(dateString);
    return date instanceof Date && !isNaN(date.getTime());
}

// 表格排序
function sortTable(table, columnIndex, dataType) {
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const header = table.querySelectorAll('th')[columnIndex];
    const direction = header.getAttribute('data-sort-direction');
    
    // 更新排序方向
    const newDirection = direction === 'asc' ? 'desc' : 'asc';
    header.setAttribute('data-sort-direction', newDirection);
    
    // 更新排序图标
    table.querySelectorAll('th .fa').forEach(icon => {
        icon.className = 'fa fa-sort';
    });
    const icon = header.querySelector('.fa');
    icon.className = newDirection === 'asc' ? 'fa fa-sort-asc' : 'fa fa-sort-desc';
    
    // 排序行
    rows.sort((a, b) => {
        const aCell = a.querySelectorAll('td')[columnIndex];
        const bCell = b.querySelectorAll('td')[columnIndex];
        
        if (!aCell || !bCell) return 0;
        
        let aValue = aCell.textContent.trim();
        let bValue = bCell.textContent.trim();
        
        // 根据数据类型进行比较
        if (dataType === 'number') {
            aValue = parseFloat(aValue.replace(/[^0-9.-]/g, ''));
            bValue = parseFloat(bValue.replace(/[^0-9.-]/g, ''));
        } else if (dataType === 'date') {
            aValue = new Date(aValue);
            bValue = new Date(bValue);
        }
        
        if (newDirection === 'asc') {
            return aValue > bValue ? 1 : aValue < bValue ? -1 : 0;
        } else {
            return aValue < bValue ? 1 : aValue > bValue ? -1 : 0;
        }
    });
    
    // 重新添加排序后的行
    rows.forEach(row => tbody.appendChild(row));
}

// 显示加载指示器
function showLoading(element) {
    // 移除之前的加载指示器
    hideLoading(element);
    
    // 创建加载指示器
    const loading = document.createElement('div');
    loading.className = 'loading-indicator';
    loading.innerHTML = '<div class="loading"></div>';
    
    // 添加到目标元素
    if (element) {
        element.appendChild(loading);
    } else {
        // 如果没有指定元素，添加到页面中央
        loading.style.position = 'fixed';
        loading.style.top = '50%';
        loading.style.left = '50%';
        loading.style.transform = 'translate(-50%, -50%)';
        loading.style.zIndex = '9999';
        document.body.appendChild(loading);
    }
}

// 隐藏加载指示器
function hideLoading(element) {
    const loadingIndicators = element ? 
        element.querySelectorAll('.loading-indicator') : 
        document.querySelectorAll('.loading-indicator');
    
    loadingIndicators.forEach(indicator => {
        indicator.remove();
    });
}

// 显示确认对话框
function confirmAction(message, callback) {
    if (confirm(message)) {
        if (typeof callback === 'function') {
            callback();
        }
        return true;
    }
    return false;
}

// 搜索功能
function setupSearch() {
    const searchInputs = document.querySelectorAll('input[name="search"]');
    searchInputs.forEach(input => {
        input.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const table = this.closest('.card').querySelector('table');
            const rows = table.querySelectorAll('tbody tr');
            
            rows.forEach(row => {
                const cells = row.querySelectorAll('td');
                let found = false;
                
                cells.forEach(cell => {
                    if (cell.textContent.toLowerCase().includes(searchTerm)) {
                        found = true;
                    }
                });
                
                row.style.display = found ? '' : 'none';
            });
        });
    });
}

// 导出功能
function exportToCSV(table, filename) {
    const rows = Array.from(table.querySelectorAll('tr'));
    const csv = [];
    
    rows.forEach(row => {
        const cells = Array.from(row.querySelectorAll('th, td'));
        const rowData = cells.map(cell => {
            // 处理包含逗号的内容
            let text = cell.textContent.trim();
            if (text.includes(',')) {
                text = `"${text}"`;
            }
            return text;
        });
        csv.push(rowData.join(','));
    });
    
    // 创建CSV文件并下载
    const csvContent = csv.join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    
    if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', filename);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}